package com.xcx.order.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.service.FileService;
import com.bootdo.common.sms.model.SmsType;
import com.bootdo.common.sms.service.AliSms;
import com.bootdo.common.utils.FileType;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.R;
import com.bootdo.lgs.order.model.LgsOrder;
import com.bootdo.lgs.order.model.LgsOrderQuery;
import com.bootdo.lgs.order.service.OrderService;
import com.bootdo.lgs.ordertrace.model.OrderTrace;
import com.xcx.order.model.SearchQuery;
import com.xcx.order.model.bind.XcxBind;
import com.xcx.order.model.XcxOrderQuery;
import com.xcx.order.service.XcxOrderService;
import com.xcx.utils.XcxUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bootdo 1992lcg@163.com
 */
@RestController
public class XcxOrderController {

    @Autowired
    private XcxOrderService xcxOrderService;

    @Autowired
    private FileService sysFileService;

    @Autowired
    private BootdoConfig bootdoConfig;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AliSms aliSms;

    //获取 短信验证码
    @GetMapping("/xcx/order/getCode")
    R getCode(XcxBind condition) {
        condition.setCode(XcxUtil.get6Str());//生成验证码
        condition.setExpireTime(XcxUtil.get30MinLater()); //生成过期时间
        if (xcxOrderService.isBindPhone(condition))//查看是否绑定过的手机号
            xcxOrderService.updateBindPhone(condition);//更新验证码和过期时间、手机型号
        else
            xcxOrderService.addBindPhone(condition);//插入验证码和过期时间、手机型号
        //发送短信
        return aliSms.send(condition.getPhoneNum(), "", SmsType.XD_XCX_BIND, "{\"code\":\"" +
                condition.getCode() +
                "\"}") ?  R.ok(): R.error();
    }

    //验证 短信验证码
    @GetMapping("/xcx/order/checkCode")
    R checkCode(XcxBind condition) {
        if (!xcxOrderService.isCodePass(condition))//检查验证码 是否匹配
            return R.error(201, "验证码错误或已失效");
        return R.ok();
    }

    //检查绑定手机是否变更
    @GetMapping("/xcx/order/checkPhone")
    R checkPhone(XcxBind condition) {
        if (xcxOrderService.isChangePhone(condition))
            return R.error();
        return R.ok();
    }

    //获取用户角色-根据手机号
    @GetMapping("/xcx/order/getUserRole")
    String getUserRole(XcxOrderQuery condition) {
        return xcxOrderService.getUserRole(condition);
    }

    //客户-查询-待收货
    @GetMapping("/xcx/order/waitReceive/list")
    List waitReceiveList(XcxOrderQuery condition) {
        xcxOrderService.initQueryCondition(5, condition);
        return xcxOrderService.getList(condition);
    }

    //客户-查询-待收货-分页
    @GetMapping("/xcx/order/waitReceive/pageList")
    PageUtils waitReceivePageList(XcxOrderQuery condition) {
        xcxOrderService.initQueryCondition(5, condition);
        List list = xcxOrderService.getList(condition);
        int total = xcxOrderService.countList(condition);
        return new PageUtils(list, total);
    }

    //客户-查询-待评价
    @GetMapping("/xcx/order/waitGrade/list")
    List waitGradeList(XcxOrderQuery condition) {
        xcxOrderService.initQueryCondition(7, condition);
        return xcxOrderService.getList(condition);
    }

    //客户-查询-待评价-分页
    @GetMapping("/xcx/order/waitGrade/pageList")
    PageUtils waitGradePageList(XcxOrderQuery condition) {
        xcxOrderService.initQueryCondition(7, condition);
        List list = xcxOrderService.getList(condition);
        int total = xcxOrderService.countList(condition);
        return new PageUtils(list, total);
    }

    //客户-查询-已完成
    @GetMapping("/xcx/order/finish/list")
    List finishList(XcxOrderQuery condition) {
        xcxOrderService.initQueryCondition(9, condition);
        return xcxOrderService.getList(condition);
    }

    //客户-查询-已完成-分页
    @GetMapping("/xcx/order/finish/pageList")
    PageUtils finishPageList(XcxOrderQuery condition) {
        xcxOrderService.initQueryCondition(9, condition);
        List list = xcxOrderService.getList(condition);
        int total = xcxOrderService.countList(condition);
        return new PageUtils(list, total);
    }

    //根据订单id、查看订单详情信息
    @GetMapping("/xcx/order/getDetail")
    LgsOrder getDetail(XcxOrderQuery condition) {
        return xcxOrderService.getDetail(condition);
    }

    //根据订单id、查看物流跟踪信息
    @GetMapping("/xcx/orderTrace/getData")
    List<OrderTrace> getData(XcxOrderQuery condition) {
        return xcxOrderService.getOrderTraceList(condition);
    }

    /**
     * 客户签收
     */
    @Log("微信小程序：客户签收订单")
    @PostMapping("/xcx/order/sign")
    public R addSign(@RequestParam Long orderId) {
        return xcxOrderService.addSign(orderId) ? R.ok() : R.error();
    }

    @ResponseBody
    @PostMapping("/xcx/file/upload")
    R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        String fileName = file.getOriginalFilename();
        fileName = FileUtil.renameToUUID(fileName);
        FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
        try {
            FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
        } catch (Exception e) {
            return R.error();
        }

        if (sysFileService.save(sysFile) > 0) {
            return R.ok().put("fileName", sysFile.getUrl());
        }
        return R.error();
    }

    /**
     * 上传评分、评论和截图
     */
    @Log("微信小程序：客户评价订单")
    @PostMapping("/xcx/order/comment")
    public R addComment(@RequestParam Long orderId, @RequestParam(required = false) Float gradeScore, @RequestParam(required = false) Float lgsScore, @RequestParam(required = false) String gradeContent, @RequestParam(required = false) String lgsContent, @RequestParam(required = false) String[] screenshots, @RequestParam(required = false) Integer is_unpack) {
        LgsOrder lgsOrder = new LgsOrder();
        lgsOrder.setId(orderId);
        if (gradeScore != null && gradeScore > 0.01)
            lgsOrder.setGrade_score(gradeScore);
        if (lgsScore != null && lgsScore > 0.01)
            lgsOrder.setLgs_score(lgsScore);
        lgsOrder.setGrade_content(gradeContent);
        lgsOrder.setLgs_content(lgsContent);
        lgsOrder.setIs_unpack(is_unpack);
        //如果需要协助拆箱、发送通知
        if (is_unpack == 1) {
            xcxOrderService.sendUnpackNotice(orderId);
        }
        if (screenshots != null && screenshots.length > 0) {
            lgsOrder.setScreenshots(StringUtils.join(Arrays.stream(screenshots).filter(StringUtils::isNotBlank).collect(Collectors.toSet()), ","));
        }

        return orderService.addComment(lgsOrder) ? R.ok() : R.error();
    }

    //物流单号查询
    @GetMapping("/xcx/order/list")
    List list(LgsOrderQuery condition) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        //过去一年
        c.setTime(new Date());
        c.add(Calendar.YEAR, -1);
        Date y = c.getTime();
        String year = format.format(y);
        condition.setOrder_start_date(year);
        return orderService.getList(condition);
    }

    //物流单号查询
    @GetMapping("/xcx/order/search/list")
    List searchList(SearchQuery condition) {
        xcxOrderService.initSearchQuery(condition);
        return xcxOrderService.searchList(condition);
    }


}
